/**
 * Created by shandianhaizan on 16/7/6.
 */


define(['validator'], function (validator) {

    function _controller($scope, $routeParams, $location, $timeout, httpService) {

        var id = $routeParams.id;
        var model ="Order";


        var isUpdate = function(){
            return id && id!=="new"
        };


        var inArray = function(one, arr){
            return $.inArray(one, arr)>=0
        };
        var inProperty = function(one , arr){
            for(var i= 0, l=arr.length; i<l; i++){
                if(one.name == arr[i].key){
                    return true;
                }
            }
            return false;
        };
        var inRelation = function(one , arr){
            for(var i= 0, l=arr.length; i<l; i++){
                if(one.objectId == arr[i].objectId){
                    return true;
                }
            }
            return false;
        };



        $scope.remove = function(one, arr){
            arr.splice( $.inArray(one, arr), 1);
        };







     $scope.validation = function(arg_params){
         if(arg_params.receiverPhone && !validator.isMobilePhone(arg_params.receiverPhone, "zh-CN")){
              return {success:false, msg:"手机号格式错误"};
            };
          //if($scope.customer){
          //    arg_params.username = $scope.customer.username;
          //}

         if(!arg_params.username || !arg_params.realName) {
             return {success:false, msg:"收件人未填写"};
         }
         if(!arg_params.production || !arg_params.production.length <=0) {
             return {success:false, msg:"未选择产品"};
         }
         if(!arg_params.payMethods){
             return {success:false, msg:"未选择支付方式"};
         }
         if(!arg_params.state){
             return {success:false, msg:"未选择状态"};
         }
         return {success:true}

        };




        $scope.save = function () {
            $scope.$broadcast('show-errors-check-validity');
            if (!$scope.userForm.$valid) return;
            var validation = $scope.validation($scope.order);
            if(!validation.success) return $scope.msg.show(validation.msg);
            httpService.save(model, $scope.order).then(function (data) {
                $scope.msg.show(data);
                if($scope.isHandleSuccess(data) && !isUpdate()){
                    $location.path('/order-detail/'+data.data.objectId);
                }
            });

        };


        $scope.searchProduction = function (keyword) {
            var query = {};
            var type = $scope.searchProType || "name";
            query[type] = keyword;
            return httpService.get("Production",query);
        };

        $scope.searchCustomerByGroup = function(keyword){
            $scope.searchCustomer().then(function(data){
                    $scope.results=data.data.data;
            }
            )
        };



        $scope.handleSeacherResult  = function (result) {
            if(result.username) $scope.order.username = result.username;
            if(result.address) $scope.order.receiverAddress = result.address;
            if(result.realName) $scope.order.receiverName = result.realName;
            if(result.mobilePhoneNumber) $scope.order.receiverPhone = result.mobilePhoneNumber;
            if(result.objectId) $scope.order.customerId = result.objectId;
            if(result.email) $scope.order.email = result.email;
        };


        $scope.searchCustomer  = function (keyword) {
            var query = {};
            var type = $scope.searchCustomerType || "name";
            query[type] = keyword;
            return httpService.get("Customer", query);
        };


        $scope.calCost = function(){
            $scope.order.cost = 0;
            $scope.order.buyCost = 0;
            angular.forEach($scope.order.production, function(p){
                $scope.order.cost = $scope.order.cost + p.cost * p.num;
                $scope.order.buyCost = $scope.order.buyCost + p.buyCost * p.num;

            });
        };


        $scope.reset = function () {
            $scope.$broadcast('show-errors-reset');
            $scope.order = {};
        };



        //添加产品
        $scope.addProduction= function(c){
            if(!c || !c.objectId) return;
            $scope.order.production =   $scope.order.production || [];
            if(!inRelation(c, $scope.order.production)) {
                var img = c.images ? c.images[0] :"";
                $scope.order.production.push({objectId: c.objectId, image:img , name: c.name ,code: c.code, cost: c.cost, num:1 , buyCost: c.cost});
            }
        };

        $scope.initGroup = function () {
            httpService.get("Group", {all:true}).then(function (data) {
                $scope.groups = data.data.data;
            });
        };
        $scope.initGroup();

        $scope.order = {
             production:[]
        }

    }

    return _controller;
});

